package cn.zqy.demo2.day14FoundationStrengthening.reflect;

import cn.zqy.demo2.day14FoundationStrengthening.Domain.Person;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 *  2. 获取构造方法们
 *        Constructor<?>[] getConstructors()
 *        Constructor<T> getConstructor(类<?>... parameterTypes)
 *
 *        Constructor<T> getDeclaredConstructor(类<?>... parameterTypes)
 *        Constructor<?>[] getDeclaredConstructors()
 *
 *        * 创建对象：
 * 			* T newInstance(Object... initargs)
 * 			* 如果使用空参数构造方法创建对象，操作可以简化：Class对象的newInstance方法
 * */
public class Demo03Constructor {
    public static void main(String[] args) throws Exception {
        //0.获取Person的Class对象
        Class personClass = Person.class;
        Constructor[] constructors = personClass.getConstructors();
        for (Constructor c : constructors) {
            System.out.println(c);
        }

        Constructor constructor = personClass.getConstructor(String.class, int.class);
        System.out.println(constructor);
        System.out.println("===============");

        // 功能
        Object p = constructor.newInstance("TOM", 56);
        System.out.println(p);

        Object c = personClass.newInstance(); // class对象创建空参对象
        System.out.println(c);

        // 打印出private修饰的构造方法
        Constructor constructor1 = personClass.getDeclaredConstructor(String.class, String.class);
        System.out.println(constructor1);
        constructor1.setAccessible(true); // 访问private修饰的一律用暴力反射
        Object kkk = constructor1.newInstance("kkk", "4564");  // 贸然赋值会报错，还是要用暴力反射
        System.out.println(kkk);
    }
}
